import java.awt.*;
import java.awt.event.KeyEvent;

public class Player {
    private static final int SPEED = 6;
    private static final int WIDTH = 60;
    private static final int HEIGHT = 80;

    private int x, y;
    private boolean left, right, shooting;
    private GamePanel gamePanel;
    private int health = 100;

    public Player(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public void setGamePanel(GamePanel gamePanel) {
        this.gamePanel = gamePanel;
    }

    public void update() {
        if (left) {
            x -= SPEED;
        }
        if (right) {
            x += SPEED;
        }
        if (shooting) {
            gamePanel.shoot();
            shooting = false;
        }

        // 边界检查
        if (x < 0) x = 0;
        if (x > 800 - WIDTH) x = 800 - WIDTH;
    }

    public void draw(Graphics2D g2d) {
        // 绘制简单的飞船
        g2d.setColor(Color.BLUE);

        // 飞船主体
        g2d.fillRect(x + 10, y, WIDTH - 20, HEIGHT - 20);

        // 飞船翅膀
        Polygon wings = new Polygon();
        wings.addPoint(x, y + 20);
        wings.addPoint(x + WIDTH, y + 20);
        wings.addPoint(x + WIDTH / 2, y + HEIGHT);
        g2d.fillPolygon(wings);

        // 驾驶舱
        g2d.setColor(Color.CYAN);
        g2d.fillOval(x + WIDTH / 4, y + 10, WIDTH / 2, HEIGHT / 4);

        // 引擎
        g2d.setColor(Color.RED);
        g2d.fillRect(x + WIDTH / 3, y + HEIGHT - 10, WIDTH / 3, 10);

        // 绘制生命值条
        g2d.setColor(Color.GREEN);
        if (health < 30) {
            g2d.setColor(Color.RED);
        } else if (health < 60) {
            g2d.setColor(Color.YELLOW);
        }
        g2d.fillRect(x, y - 10, health * WIDTH / 100, 5);
    }

    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();
        if (key == KeyEvent.VK_LEFT) {
            left = true;
        }
        if (key == KeyEvent.VK_RIGHT) {
            right = true;
        }
        if (key == KeyEvent.VK_SPACE) {
            shooting = true;
        }
    }

    public void keyReleased(KeyEvent e) {
        int key = e.getKeyCode();
        if (key == KeyEvent.VK_LEFT) {
            left = false;
        }
        if (key == KeyEvent.VK_RIGHT) {
            right = false;
        }
        if (key == KeyEvent.VK_SPACE) {
            shooting = false;
        }
    }

    public Rectangle getBounds() {
        return new Rectangle(x, y, WIDTH, HEIGHT);
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public int getWidth() {
        return WIDTH;
    }

    public int getHealth() {
        return health;
    }
}    